import  { AppPostT } from '@/utils/request'
import  { encryptSh256 } from '@/utils/tool'
import { getLocalUserInfo } from "@/utils";
import { Area, RedirectUrl, TraceParams, TraceResponse } from '@/models/misc'

// 获取省市区树形列表
export async function getAreas() {
    const res = await AppPostT<Area[]>("/misc/areaTree")
    console.log("getAreas request:", {}, ", result:", res)
    return res.data ? res.data : [] as Area[]
}

// 获取Scnet跳转URL
export async function getScnetRedirectUrl() {
    const data = {}
    const res = await AppPostT<RedirectUrl>("/user/getScnetRedirectUrl", data, { silent: true })
    console.log("getScnetRedirectUrl request:", data, ", result:", res)
    return res.data ? res.data : {} as RedirectUrl
}

// 获取Scnet跳转URL
export async function getRedirectUrl(defaultUrl: string = "") {
    let url = defaultUrl;
    try {
        const data = {}
        const res = await AppPostT<RedirectUrl>("/user/getScnetRedirectUrl", data, { silent: true })
        if (res && res.data && res.data.url) {
            url = res.data.url;
        }
    } catch(err) {

    }
    console.log("getRedirectUrl defaultUrl: ", defaultUrl, ", result: ", url)
    return url;
}

// 学习课程
export async function traceViewCourse(courseId: string | number) {
    const userId = getLocalUserInfo()?.id || 0;
    const data = {
        trackKey: "courseView",
        userId: `${userId}`,
        param1: `${courseId}`,
    } as TraceParams;
    return await reportTrack(data);
}

// 浏览文档
export async function traceViewDoc(documentPkgId: string | number, documentId: string | undefined = undefined) {
    const userId = getLocalUserInfo()?.id || 0;
    const data = {
        trackKey: "docView",
        userId: `${userId}`,
        param1: `${documentPkgId}`,
        param2: `${documentId ? documentId : ''}`,
    } as TraceParams;
    return await reportTrack(data);
}

// 浏览页面
export async function traceViewPage(pagePath: string, data1: number | string | undefined = undefined, data2: number | string | undefined = undefined) {
    const userId = getLocalUserInfo()?.id || 0;
    const data = {
        trackKey: "pageView",
        userId: `${userId ? userId : ''}`,
        param1: pagePath,
        param2: data1 ? `${data1}` : undefined,
        param3: data2 ? `${data2}` : undefined,
    } as TraceParams;
    return await reportTrack(data);
}

// 点击banner
export async function traceClickBanner(bannerId: string | number) {
    const userId = getLocalUserInfo()?.id || 0;
    const data = {
        trackKey: "clickBanner",
        userId: `${userId}`,
        param1: `${bannerId}`,
    } as TraceParams;
    return await reportTrack(data);
}

// 上报埋点（后台请求）
export async function reportTrack(data: TraceParams) {
    const result = {};
    const timestamp = new Date().getTime();
    const nonce = Math.random().toString(36).substring(2);
    const sign = encryptSh256({ timestamp, nonce, data});
    const headers = {
        timestamp,
        nonce,
        sign,
        client_request_id: Math.random().toString(36).substring(2),
        "Content-Type": "application/json"
    }
    try {
        const res = await AppPostT<TraceResponse>("/track/report", data, { headers, silent: true })
        console.log("reportTrack request:", data, ", result:", res)
        return res.data ? res.data : {} as TraceResponse
    } catch(err) {

    }
    return result;
}
